<template>
  <div class="app-container">

    <div class="header">
      <el-button type="primary" @click="dialogSaveUserForm = true" size="mini">添加</el-button>
      <el-input style="width: 300px; margin-left: 100px;" size="mini" placeholder="输入关键字搜索" v-model="userListForm.memo" @change="userSearch" @input="checkVal">
        <i slot="suffix" class="el-icon-search" ></i>
      </el-input>
    </div>

    <!-- 添加弹出框 -->
    <el-dialog title="添加" :visible.sync="dialogSaveUserForm" :close-on-click-modal="false" @close="onCancel">
      <el-form ref="form" :model="form" label-width="100px" :rules="saveRules">
        <el-form-item label="账号" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="昵称" prop="nick">
          <el-input v-model="form.nick" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password />
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="loading">提交</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改学生弹出框 -->
    <el-dialog title="修改学生" :visible.sync="dialpgEditUserForm" :close-on-click-modal="false" @close="closeEdit">
      <el-form ref="editForm" :model="editForm" label-width="100px" :rules="editRules">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="editForm.studentId" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="edit">提交</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 学生列表 -->
    <div class="content">
      <el-table :data="userList" style="width: 100%;" stripe :default-sort="{ prop: 'date', order: 'descending' }">
        <el-table-column label="学生信息">
          <el-table-column label="账号" width="260" prop="name">
            <template slot-scope="scope">
              <div>{{ scope.row.userName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="昵称" width="260" prop="nick">
            <template slot-scope="scope">
              <div>{{ scope.row.userNick }}</div>
            </template>
          </el-table-column>
          <el-table-column label="学号" width="260" prop="phone">
            <template slot-scope="scope">
              <div>{{ scope.row.studentId }}</div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="操作">
          <el-table-column label="修改">
            <template slot-scope="scope">
              <el-button type="primary" circle icon="el-icon-edit" @click="showEdit(scope.row.userId)"></el-button>
            </template>
          </el-table-column>
          <el-table-column label="删除">
            <template slot-scope="scope">
              <el-button type="danger" circle icon="el-icon-delete" @click="delUser(scope.row.userId)"></el-button>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="adminListSizeChange" @current-change="adminListCurrentChange"
        :page-size="userListForm.size" :page-sizes="[10, 20, 30]" layout="total, sizes, prev, pager, next"
        :total="userListTotal" style="margin-top: 20px;">
      </el-pagination>
    </div>


  </div>
</template>

<script>
import utils from '@/utils/checkLogin'
import { Message } from 'element-ui'
import { saveUser, getUserList, deleteUser, getUpdateUserInfo, editUser } from '@/api/api'

export default {
  data() {
    return {
      loading: false,
      form: {
        name: '',
        password: '',
        nick: '',
        studentId: '',
      },
      dialogSaveUserForm: false,
      saveRules: {
        name: [
          { required: true, message: '请输入账号', trigger: 'change' },
          { min: 5, max: 10, message: '账号长度在 5 到 10 个字符', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'change' }
        ],
        nick: [
          { required: true, message: '请输入昵称', trigger: 'change' },
          { max: 5, message: '昵称长度最高 5 个字符', trigger: 'change' }
        ],
        studentId: [
          { required: true, message: '请输入学号', trigger: 'change' },
          { type: 'number', message: '输入的值必须为数字', trigger: 'blur', transform: (value) => Number(value) }
        ],
      },
      userList: [],
      userListForm: {
        page: 1,
        size: 10,
        memo: ''
      },
      userListTotal: 0,
      editForm: {
        userId: null,
        studentId: '',
        password: '',
      },
      dialpgEditUserForm: false,
      editRules: {
        studentId: [
          { required: true, message: '请输入学号', trigger: 'change' },
          { type: 'number', message: '输入的值必须为数字', trigger: 'blur', transform: (value) => Number(value) }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'change' }
        ],
      },
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        // 表单验证失败
        if (!valid) {
          Message({
            message: '请检查表单！',
            type: 'warning',
            duration: 2000
          })
          return false
        } else {
          // 表单验证成功
          console.log(JSON.stringify(this.form));
          saveUser(this.form).then((res) => {
            if (res.code == 200) {
              Message({
                message: '添加成功',
                type: 'success',
                duration: 3000
              })
              console.log('添加学生', res)
              this.loading = true
              setTimeout(() => {
                this.dialogSaveUserForm = false
                this.loading = false
                this.getUserListData()
                this.$nextTick(() => {
                  // 添加成功时，置空 form 表单
                  this.$refs.form.resetFields()
                })
              }, 2000)
            }
          })
        }
      })

    },
    onCancel() {
      this.dialogSaveUserForm = false
      this.$nextTick(() => {
        // 关掉 dialog 时，置空 form 表单
        this.$refs.form.resetFields()
      })

    },
    getUserListData() {
      getUserList(this.userListForm).then((res) => {
        if (res.code == 200) {
          console.log('学生列表', res);
          this.userList = res.data
          this.userListTotal = res.total
        }
      })
    },
    // 学生列表，切换每页条数时
    adminListSizeChange(e) {
      this.userListForm.size = e
      this.getUserListData()
    },

    // 学生列表，点击切换页码时
    adminListCurrentChange(e) {
      this.userListForm.page = e
      this.getUserListData()
    },

    // 展示修改弹出框
    showEdit(userId) {
      this.dialpgEditUserForm = true
      this.editForm.userId = userId
      // 数据回显
      getUpdateUserInfo(userId).then((res) => {
        if (res.code == 200) {
          console.log('修改学生（数据回显）', res)
          this.editForm.studentId = res.data.studentId
          this.editForm.password = res.data.password
        }
      })
    },

    // 关闭修改弹出框
    closeEdit() {
      this.dialpgEditUserForm = false
    },

    // 编辑-提交
    edit() {
      this.$refs.editForm.validate(valid => {
        if (!valid) {
          Message({
            message: '请检查表单！',
            type: 'warning',
            duration: 2000
          })
          return false;
        } else {
          editUser(this.editForm).then((res) => {
            if (res.code == 200) {
              console.log('修改学生', res);
              Message({
                message: '修改成功',
                type: 'success',
                duration: 3000
              })
              this.loading = true
              setTimeout(() => {
                this.dialpgEditUserForm = false
                this.loading = false
              }, 2000)
              this.getUserListData()
            }
          })
        }
      })
    },

    // 取消编辑
    cancelEdit() {
      this.dialpgEditUserForm = false
    },

    delUser(id) {
      let obj = {
        id,
      }
      this.$confirm('是否删除该学生?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(obj).then((res) => {
          if (res.code == 200) {
            console.log('删除成功', res);
            this.$message({
              type: 'success',
              message: '删除成功',
              duration: 3000
            })
            this.getUserListData()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 3000
            })
          }
        })
      }).catch(() => {
      })

    },
    // 搜索
    userSearch() {
      console.log(JSON.stringify(this.userListForm))
      this.getUserListData()
    },
    // 如果搜索框的值为空，刷新一下商品列表
    checkVal() {
      if (this.userListForm.memo == '') {
        this.getUserListData()  
      }
    }
  },
  created() {
    utils.checkLogin()
    this.getUserListData()
  }
}
</script>

<style lang="less" scoped>
.app-container {
  padding: 40px;

  .header {
    align-items: center;
    display: flex;
    margin-bottom: 20px;

    .el-icon-search {
      cursor: pointer;
      margin-right: 4px;
      margin-top: 8px;
    }
  }

  .content {
    text-align: center;
  }
}
</style>

